Vue3.0在template、script、style中引用图片资源的方式 您所在的位置:网站首页 whatsapp 引用图片 Vue3.0在template、script、style中引用图片资源的方式

Vue3.0在template、script、style中引用图片资源的方式

2023-12-03 02:02| 来源: 网络整理| 查看: 265

alias别名配置和css全局变量设置

在vue.config.js中通过config.resolve.alias设置别名,通过css设置scss的全局变量

@ 就代表src 所以也可以这么写 .set(‘views’, resolve(’@/views’))

module.exports = { lintOnSave: true, baseUrl: './', productionSourceMap: true, chainWebpack: config => { config.resolve.alias .set('@', resolve('src')) .set('views', resolve('src/views')) .set('assets', resolve('src/assets')) .set('public', resolve('public')) .set('styles', resolve('src/styles')) .set('static', resolve('public/static')) .set('components', resolve('src/components')); }, css: { loaderOptions: { sass: { data: `@import "~@/styles/variables.scss";` } } } }; template模板内引用图片

通过config.resolve.alias设置的别名在Vue的template模板和style样式内使用前面需加上~,告诉加载器它是一个模块,而不是相对路径

style样式内引用图片 .bg { background: url("~static/images/logo.png"); } .bg1 { background: url("~assets/logo.png") no-repeat; } script脚本内引用图片

template模块

script脚本

data() { return { //引用public文件夹下的图片 imgUrl1: `static/images/logo.png`, imgUrl2: `./static/images/logo.png`, imgUrl3: `../../static/images/logo.png`, //引用assets文件夹下的图片 imgUrl4: require("assets/logo.png"), } }

1: data中引用public/static中的图片只能使用static/images/logo.png或者./static/images/logo.png或者…/…/static/images/logo.png这三种方式引用图片 注意:这里的static不是别名,并且在script中引入static中的图片时也不能使用别名。

2: data中引用assets图片时,必须使用require(‘xxx’)方式引用,否则会当字符串处理而无法显示图片。 注意:这里assets是别名,也可以通过相对路径使用

为什么不能public/static/images/logo.png引入呢?

可能是因为在执行npm run build后,新生成的dist文件内没有public文件夹,而是会把public文件夹下的所有文件或文件夹放到dist根目录下。此时就找不到public路径了,因为public文件夹下有static文件夹,所以可以使用static/xxx引用图片,如 在这里插入图片描述

script脚本内引用资源

在script脚本中通过import引用其他资源时,则直接使用别名,不需加~。

import demo from 'views/Demo'; //引用其他组件 import 'styles/Demo.css'; //引用样式 style中引用全局变量

通过在vue.config.js的css中加载Sass的全局变量类variables.scss,则在任意一个Style样式内都可以引用variables.scss内定义的属性,如

variables.scss类

$RED:#f00;

style样式

.global_style_bg { background: $RED; }

这种定义的全局的属性,只能在style样式内使用,在template和script都不可使用

自定义变量

在css中我们可以给body样式设置自定义变量来让整个项目使用 css自定义变量的语法是:–* 变量使用的语法是:var(–*)

body { /* 定义公共色值 */ --F00: #F00; /* 定义默认字体大小 */ --size: 18px; /* 可直接使用 */ font-size: var(--size); --bg: var(--F00); } 自定义变量的使用

style样式

.style_bg { background-color: var(--F00); font-size: var(--size); }

script脚本

data() { return { bgColor: 'var(--00F)', } },


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有